<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生成绩分析系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <script src="js/echarts.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }

        :root {
            --primary: #4F46E5;
            --primary-dark: #4338CA;
            --secondary: #10B981;
            --tertiary: #F59E0B;
            --light: #F9FAFB;
            --dark: #1F2937;
            --gray: #6B7280;
            --light-gray: #E5E7EB;
            --border: #D1D5DB;
            --card-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            --success: #10B981;
            --warning: #F59E0B;
            --improvement: #ff4d4f;
            /* 红色表示上升/进步 */
            --decline: #52c41a;
            /* 绿色表示下降/退步 */
        }

        body {
            background: linear-gradient(135deg, #f0f7ff 0%, #f8fafc 100%);
            color: var(--dark);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        header {
            background: white;
            border-radius: 16px;
            box-shadow: var(--card-shadow);
            padding: 20px 30px;
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 20px;
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 1.5rem;
            font-weight: 700;
            color: var(--primary);
        }

        .logo i {
            font-size: 1.8rem;
        }

        .header-controls {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            margin-top: 15px;
        }

        .class-filter {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        select {
            padding: 10px 15px;
            border-radius: 8px;
            border: 1px solid var(--border);
            background: white;
            font-size: 1rem;
            min-width: 150px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .action-btn {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            background: var(--light);
            color: var(--gray);
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .action-btn:hover {
            background: var(--primary);
            color: white;
            transform: scale(1.1);
        }

        select:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.2);
        }

        .file-upload {
            position: relative;
            display: inline-block;
        }

        .file-upload-btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            background: var(--primary);
            color: white;
            padding: 10px 20px;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            border: none;
        }

        .file-upload-btn:hover {
            background: var(--primary-dark);
            transform: translateY(-2px);
        }

        .file-upload-btn.update {
            background: #60A5FA;
        }

        .file-upload-btn.reset {
            background: #DC2626;
        }

        .file-upload-btn.export {
            background: #16A34A;
        }

        #file-input {
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            width: 100%;
            height: 100%;
            cursor: pointer;
        }

        .stats {
            display: flex;
            gap: 15px;
            margin-top: 10px;
            flex-wrap: wrap;
        }

        .stat-card {
            background: var(--light);
            border-radius: 10px;
            padding: 12px 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            min-width: 180px;
        }

        .stat-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
        }

        .stat-content {
            display: flex;
            flex-direction: column;
        }

        .stat-value {
            font-size: 1.4rem;
            font-weight: 700;
        }

        .stat-label {
            font-size: 0.9rem;
            color: var(--gray);
        }

        .table-container {
            background: white;
            border-radius: 16px;
            box-shadow: var(--card-shadow);
            padding: 25px;
            overflow-x: auto;
        }

        .table-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .table-title {
            font-size: 1.5rem;
            font-weight: 600;
            color: var(--dark);
        }

        .search-box {
            display: flex;
            align-items: center;
            background: var(--light);
            border-radius: 8px;
            padding: 8px 15px;
            border: 1px solid var(--border);
        }

        .search-box input {
            border: none;
            background: transparent;
            padding: 5px 10px;
            font-size: 1rem;
            min-width: 215px;
        }

        .search-box input:focus {
            outline: none;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        thead {
            background: var(--light);
        }

        th {
            padding: 15px;
            text-align: left;
            font-weight: 600;
            color: var(--dark);
            border-bottom: 2px solid var(--border);
            position: relative;
        }

        th:hover {
            background: #f3f4f6;
        }

        .sort-icon {
            position: absolute;
            right: 10px;
            color: var(--gray);
            font-size: 0.8rem;
        }

        td {
            padding: 15px;
            border-bottom: 1px solid var(--border);
        }

        tr:last-child td {
            border-bottom: none;
        }

        tr:hover {
            background: rgba(79, 70, 229, 0.05);
        }

        .student-id {
            font-weight: 600;
            color: var(--primary);
        }

        .class-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
            background: #DBEAFE;
            color: #1D4ED8;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: var(--gray);
        }

        .empty-state i {
            font-size: 4rem;
            color: var(--light-gray);
            margin-bottom: 20px;
        }

        .empty-state p {
            font-size: 1.2rem;
            max-width: 500px;
            margin: 0 auto;
        }

        .file-requirements {
            background: #F3F4F6;
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
            font-size: 0.9rem;
        }

        .file-requirements h4 {
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        footer {
            text-align: center;
            padding: 30px 0;
            color: var(--gray);
            margin-top: 40px;
        }

        /* 模态框样式 */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }

        .modal-overlay.active {
            opacity: 1;
            visibility: visible;
        }

        .modal-content {
            background: white;
            border-radius: 16px;
            width: 90%;
            max-width: 1000px;
            max-height: 90vh;
            overflow-y: auto;
            padding: 30px;
            position: relative;
            transform: translateY(50px);
            transition: transform 0.3s ease;
        }

        .modal-overlay.active .modal-content {
            transform: translateY(0);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid var(--border);
        }

        .modal-title {
            font-size: 1.8rem;
            color: var(--primary);
        }

        .close-modal {
            background: none;
            border: none;
            font-size: 1.8rem;
            cursor: pointer;
            color: var(--gray);
            transition: color 0.3s;
        }

        .close-modal:hover {
            color: var(--dark);
        }

        .student-info {
            display: flex;
            gap: 20px;
            margin-bottom: 30px;
            flex-wrap: wrap;
        }

        .info-card {
            background: var(--light);
            border-radius: 12px;
            padding: 20px;
            flex: 1;
            min-width: 200px;
        }

        .info-card h3 {
            margin-bottom: 15px;
            color: var(--gray);
            font-size: 1.1rem;
        }

        .info-value {
            font-size: 2rem;
            font-weight: 700;
            color: var(--primary);
        }

        .info-label {
            font-size: 0.9rem;
            color: var(--gray);
            margin-top: 5px;
        }

        .chart-container {
            height: 350px;
            margin: 30px 0;
            border-radius: 12px;
            overflow: hidden;
        }

        .detail-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 30px;
        }

        .detail-table th {
            background: var(--primary);
            color: white;
        }

        .detail-table th,
        .detail-table td {
            padding: 12px 15px;
            text-align: center;
        }

        .detail-table tr:nth-child(even) {
            background: var(--light);
        }

        .detail-table tr:hover {
            background: rgba(79, 70, 229, 0.1);
        }

        /* 变化趋势样式 */
        .improvement {
            color: var(--improvement);
            font-weight: bold;
        }

        .decline {
            color: var(--decline);
            font-weight: bold;
        }

        .change-trend {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 4px;
        }

        @media (max-width: 768px) {
            header {
                flex-direction: column;
                align-items: flex-start;
            }

            .header-controls {
                width: 100%;
            }

            .class-filter,
            .file-upload {
                width: 100%;
            }

            select {
                width: 100%;
            }

            .file-upload-btn {
                width: 100%;
                justify-content: center;
            }

            .stats {
                width: 100%;
            }

            .stat-card {
                flex: 1;
                min-width: 0;
            }

            th,
            td {
                padding: 10px;
                font-size: 0.9rem;
            }

            .modal-content {
                padding: 20px;
            }

            .chart-container {
                height: 300px;
            }

            .student-info {
                flex-direction: column;
            }
        }

        @media (max-width: 480px) {
            .table-header {
                flex-direction: column;
                align-items: flex-start;
            }

            .search-box {
                width: 100%;
            }

            .search-box input {
                width: 100%;
            }

            .logo span {
                font-size: 1.2rem;
            }

            .modal-content {
                width: 95%;
                padding: 15px;
            }

            .modal-title {
                font-size: 1.5rem;
            }

            .chart-container {
                height: 250px;
            }

            .detail-table th,
            .detail-table td {
                padding: 8px 5px;
                font-size: 0.8rem;
            }
        }
    </style>
</head>

<body>

    <div class="container">
        <header>
            <div class="logo">
                <i class="fas fa-user-graduate"></i>
                <span>学生成绩分析系统</span>
            </div>

            <div class="header-controls">
                <div class="file-upload">
                    <button class="file-upload-btn">
                        <i class="fas fa-file-upload"></i>
                        上传Excel数据
                    </button>
                    <input type="file" id="file-input" accept=".xlsx, .xls">
                </div>
                <div class="file-upload">
                    <button class="file-upload-btn update">
                        <i class="fas fa-sync"></i> 更新数据
                    </button>

                    <button class="file-upload-btn reset">
                        <i class="fas fa-trash"></i> 重置数据
                    </button>

                    <button class="file-upload-btn export">
                        <i class="fas fa-download"></i> 导出数据
                    </button>
                </div>
                <div class="class-filter">
                    <label for="class-select"><i class="fas fa-filter"></i> 班级筛选：</label>
                    <select id="class-select">
                        <option value="all">全部班级</option>
                        <!-- 班级选项将动态生成 -->
                    </select>
                </div>
            </div>

            <div class="stats">
                <div class="stat-card">
                    <div class="stat-icon" style="background: #DBEAFE; color: #1D4ED8;">
                        <i class="fas fa-users"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-value" id="total-students">0</div>
                        <div class="stat-label">学生总数</div>
                    </div>
                </div>

                <div class="stat-card">
                    <div class="stat-icon" style="background: #D1FAE5; color: #047857;">
                        <i class="fas fa-chalkboard-teacher"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-value" id="class-count">0</div>
                        <div class="stat-label">班级数量</div>
                    </div>
                </div>

                <div class="stat-card">
                    <div class="stat-icon" style="background: #FEF3C7; color: #B45309;">
                        <i class="fas fa-chart-line"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-value" id="exam-count">0</div>
                        <div class="stat-label">考试总数</div>
                    </div>
                </div>
            </div>
        </header>

        <div class="table-container">
            <div class="table-header">
                <h2 class="table-title">学生信息列表</h2>
                <div class="search-box">
                    <i class="fas fa-search"></i>
                    <input type="text" id="search-input" placeholder="搜索学生姓名、考号或座号">
                </div>
            </div>

            <div id="table-content">
                <div class="empty-state">
                    <i class="fas fa-file-excel"></i>
                    <h3>暂无学生数据</h3>
                    <p>请上传Excel文件以加载学生数据</p>
                </div>
            </div>

            <div class="file-requirements">
                <h4><i class="fas fa-info-circle"></i> Excel文件要求：</h4>
                <p>表格必须包含以下列：<strong>班级</strong>、<strong>姓名</strong>、<strong>考号</strong>、<strong>座号</strong></p>
                <p>第一行应为表头，数据从第二行开始</p>
            </div>
        </div>

        <footer>
            <p>© 2025 学生成绩分析系统 | 数据仅保存在浏览器内存中</p>
        </footer>
    </div>

    <!-- 学生成绩分析模态框 -->
    <div class="modal-overlay" id="student-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title">学生成绩趋势分析</h2>
                <button class="close-modal">&times;</button>
            </div>

            <div id="student-details">
                <div class="student-info">
                    <div class="info-card">
                        <h3>学生姓名</h3>
                        <div class="info-value" id="student-name">--</div>
                        <div class="info-label">姓名</div>
                    </div>

                    <div class="info-card">
                        <h3>班级</h3>
                        <div class="info-value" id="student-class">--</div>
                        <div class="info-label">班级</div>
                    </div>

                    <div class="info-card">
                        <h3>考号</h3>
                        <div class="info-value" id="student-id">--</div>
                        <div class="info-label">考号</div>
                    </div>

                    <div class="info-card">
                        <h3>座号</h3>
                        <div class="info-value" id="student-seat">--</div>
                        <div class="info-label">座号</div>
                    </div>
                </div>

                <div class="chart-container" id="performance-chart"></div>

                <h3>详细成绩数据</h3>
                <table class="detail-table">
                    <thead>
                        <tr>
                            <th>考试名称</th>
                            <th>成绩</th>
                            <th>分变化</th>
                            <th>班级排名</th>
                            <th>班名变化</th>
                            <th>年级排名</th>
                            <th>级名变化</th>
                        </tr>
                    </thead>
                    <tbody id="exam-details">
                        <!-- 成绩数据将通过JS动态填充 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        // 中文表头到英文字段的映射
        const columnMapping = {
            '班级': 'class',
            '姓名': 'name',
            '考号': 'id',
            '座号': 'seat'
        };

        // DOM元素
        const fileInput = document.getElementById('file-input');
        const classSelect = document.getElementById('class-select');
        const searchInput = document.getElementById('search-input');
        const tableContent = document.getElementById('table-content');
        const totalStudents = document.getElementById('total-students');
        const classCount = document.getElementById('class-count');
        const examCount = document.getElementById('exam-count');
        const updateBtn = document.querySelector('.update');
        const resetBtn = document.querySelector('.reset');
        const exportBtn = document.querySelector('.export');

        // 模态框相关元素
        const studentModal = document.getElementById('student-modal');
        const closeModalBtn = document.querySelector('.close-modal');
        const studentNameEl = document.getElementById('student-name');
        const studentClassEl = document.getElementById('student-class');
        const studentIdEl = document.getElementById('student-id');
        const studentSeatEl = document.getElementById('student-seat');
        const examDetailsEl = document.getElementById('exam-details');
        const performanceChart = document.getElementById('performance-chart');

        // 当前展示的数据
        let currentData = [];
        const STORAGE_KEY = 'student_data';

        // 模拟考试数据
        const mockExams = JSON.parse(localStorage.getItem('exams')) || [];

        // const mockExams = {
        //     "week7": {
        //         "id": "week7",
        //         "name": "第七周考试",
        //         "url": "https://zc-oss2.oss-cn-hongkong.aliyuncs.com/lhsz/%E7%AC%AC%E4%B8%83%E5%91%A8.xlsx",
        //         "des": "期中模拟考试",
        //         "data": [
        //             { "class": 701, "name": "司子烁", "id": "8230240004", "seat": "04", "score": 116, "gradeRank": 1, "classRank": 1 },
        //             { "class": 712, "name": "田淑萍", "id": "8230240590", "seat": "10", "score": 116, "gradeRank": 1, "classRank": 1 },
        //             { "class": 716, "name": "娄雨晴", "id": "8230240798", "seat": "07", "score": 116, "gradeRank": 1, "classRank": 1 },
        //             { "class": 701, "name": "李紫欣", "id": "8230240003", "seat": "03", "score": 114, "gradeRank": 4, "classRank": 2 },
        //             { "class": 720, "name": "何思琪", "id": "8230241033", "seat": "06", "score": 113, "gradeRank": 5, "classRank": 1 },
        //             { "class": 711, "name": "李伊然", "id": "8230240529", "seat": "02", "score": 112, "gradeRank": 6, "classRank": 1 }
        //         ]
        //     },
        //     "week6": {
        //         "id": "week6",
        //         "name": "第六周考试",
        //         "url": "https://zc-oss2.oss-cn-hongkong.aliyuncs.com/lhsz/%E7%AC%AC%E5%85%AD%E5%91%A8.xlsx",
        //         "des": "单元测试",
        //         "data": [
        //             { "class": 701, "name": "司子烁", "id": "8230240004", "seat": "04", "score": 112, "gradeRank": 2, "classRank": 1 },
        //             { "class": 712, "name": "田淑萍", "id": "8230240590", "seat": "10", "score": 108, "gradeRank": 5, "classRank": 1 },
        //             { "class": 716, "name": "娄雨晴", "id": "8230240798", "seat": "07", "score": 105, "gradeRank": 8, "classRank": 2 },
        //             { "class": 701, "name": "李紫欣", "id": "8230240003", "seat": "03", "score": 110, "gradeRank": 3, "classRank": 2 },
        //             { "class": 720, "name": "何思琪", "id": "8230241033", "seat": "06", "score": 115, "gradeRank": 1, "classRank": 1 },
        //             { "class": 711, "name": "李伊然", "id": "8230240529", "seat": "02", "score": 104, "gradeRank": 10, "classRank": 1 }
        //         ]
        //     },
        //     "week5": {
        //         "id": "week5",
        //         "name": "第五周考试",
        //         "url": "https://zc-oss2.oss-cn-hongkong.aliyuncs.com/lhsz/%E7%AC%AC%E4%BA%94%E5%91%A8.xlsx",
        //         "des": "随堂测验",
        //         "data": [
        //             { "class": 701, "name": "司子烁", "id": "8230240004", "seat": "04", "score": 105, "gradeRank": 5, "classRank": 1 },
        //             { "class": 712, "name": "田淑萍", "id": "8230240590", "seat": "10", "score": 100, "gradeRank": 8, "classRank": 3 },
        //             { "class": 716, "name": "娄雨晴", "id": "8230240798", "seat": "07", "score": 98, "gradeRank": 12, "classRank": 3 },
        //             { "class": 701, "name": "李紫欣", "id": "8230240003", "seat": "03", "score": 102, "gradeRank": 6, "classRank": 2 },
        //             { "class": 720, "name": "何思琪", "id": "8230241033", "seat": "06", "score": 108, "gradeRank": 2, "classRank": 1 },
        //             { "class": 711, "name": "李伊然", "id": "8230240529", "seat": "02", "score": 95, "gradeRank": 15, "classRank": 2 }
        //         ]
        //     }
        // };

        // 从本地存储加载数据
        function loadLocalData() {
            const data = localStorage.getItem(STORAGE_KEY);
            return data ? JSON.parse(data) : null;
        }

        // 保存数据到本地存储
        function saveLocalData(data) {
            localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
        }

        // 从网络获取学生名单Excel数据
        async function fetchExcelData() {
            try {
                const response = await fetch('https://zc-oss2.oss-cn-hongkong.aliyuncs.com/lhsz/%E7%AC%AC%E4%B8%83%E5%91%A8.xlsx', {
                    mode: 'cors',
                    headers: {
                        'Origin': location.origin
                    }
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const arrayBuffer = await response.arrayBuffer();
                const data = new Uint8Array(arrayBuffer);
                const workbook = XLSX.read(data, { type: 'array' });
                const worksheet = workbook.Sheets[workbook.SheetNames[0]];
                return XLSX.utils.sheet_to_json(worksheet);
            } catch (error) {
                console.error('网络请求详细错误:', error);
                alert(`网络请求失败: ${error.message}\n请检查网络连接或手动上传文件`);
                return null;
            }
        }

        // 处理Excel数据
        function processExcelData(data) {
            return data.map(row => {
                const newRow = {};
                for (const [chineseHeader, englishField] of Object.entries(columnMapping)) {
                    if (row[chineseHeader] !== undefined) {
                        newRow[englishField] = row[chineseHeader];
                    }
                }
                return newRow;
            });
        }

        // 处理数据并更新UI
        function processData(data) {
            currentData = data;
            saveLocalData(data);
            updateStats(data);
            updateClassSelect(data);
            renderTable(data);
        }

        // 显示初始空状态
        function showInitialEmptyState(errorMessage = '') {
            tableContent.innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-exclamation-triangle"></i>
                    <h3>${errorMessage ? '数据加载失败' : '欢迎使用'}</h3>
                    <p>${errorMessage || '正在加载初始数据...'}</p>
                    ${errorMessage ? '<button onclick="fileInput.click()" class="file-upload-btn" style="margin-top: 20px">点击重试</button>' : ''}
                </div>
            `;
        }

        // 更新统计信息
        function updateStats(data) {
            totalStudents.textContent = data.length;

            const classes = new Set(data.map(student => student.class));
            classCount.textContent = classes.size;

            examCount.textContent = Object.keys(mockExams).length;
        }

        // 更新班级筛选下拉菜单
        function updateClassSelect(data) {
            while (classSelect.options.length > 1) {
                classSelect.remove(1);
            }

            const classes = [...new Set(data.map(student => student.class))];
            classes.sort((a, b) => {
                const numA = parseInt(a);
                const numB = parseInt(b);
                return !isNaN(numA) && !isNaN(numB) ? numA - numB : a.toString().localeCompare(b.toString());
            });

            classes.forEach(cls => {
                const option = document.createElement('option');
                option.value = cls;
                option.textContent = `班级 ${cls}`;
                classSelect.appendChild(option);
            });
        }

        // 渲染表格
        function renderTable(data) {
            if (data.length === 0) {
                tableContent.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-user-slash"></i>
                        <h3>没有符合条件的学生</h3>
                        <p>请尝试更改筛选条件或搜索关键词</p>
                    </div>
                `;
                return;
            }

            let tableHTML = `
                <table>
                    <thead>
                        <tr>
                            <th>考号</th>
                            <th>姓名</th>
                            <th>班级</th>
                            <th>座号</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

            data.forEach(student => {
                tableHTML += `
                    <tr>
                        <td class="student-id">${student.id || '未提供'}</td>
                        <td>${student.name || '未提供'}</td>
                        <td><span class="class-badge">${student.class || '未提供'}</span></td>
                        <td>${student.seat || '未提供'}</td>
                        <td>
                            <div class="actions">
                                <div class="action-btn" title="查看详情" onclick="viewStudent('${student.id}')">
                                    <i class="fas fa-eye"></i>
                                </div>
                            </div>
                        </td>
                    </tr>
                `;
            });

            tableHTML += `
                    </tbody>
                </table>
            `;

            tableContent.innerHTML = tableHTML;
        }

        // 班级筛选
        classSelect.addEventListener('change', function () {
            filterData();
        });

        // 搜索功能
        searchInput.addEventListener('input', function () {
            filterData();
        });

        // 查看学生详情
        function viewStudent(studentId) {
            const student = currentData.find(s => s.id === studentId);
            if (student) {
                // 显示学生基本信息
                studentNameEl.textContent = student.name || '未提供';
                studentClassEl.textContent = student.class || '未提供';
                studentIdEl.textContent = student.id || '未提供';
                studentSeatEl.textContent = student.seat || '未提供';

                // 获取该学生的所有考试数据
                const studentExams = getStudentExams(studentId);

                // 更新考试详情表格
                updateExamDetails(studentExams);

                // 绘制成绩趋势图
                renderPerformanceChart(studentExams);

                // 显示模态框
                studentModal.classList.add('active');
            }
        }

        // 获取学生的所有考试数据
        function getStudentExams(studentId) {
            const exams = [];

            // 遍历所有考试
            for (const examKey in mockExams) {
                const exam = mockExams[examKey];
                // 在该次考试中查找学生
                const studentExam = exam.data.find(item => item.id === studentId);

                if (studentExam) {
                    exams.push({
                        examId: exam.id,
                        examName: exam.name,
                        score: studentExam.score,
                        gradeRank: studentExam.gradeRank,
                        classRank: studentExam.classRank,
                        examDescription: exam.des
                    });
                }
            }

            // 按考试ID排序（这里假设考试ID按时间顺序）
            exams.sort((a, b) => a.examId.localeCompare(b.examId));

            return exams;
        }

        // 更新考试详情表格（新增差值比较功能）
        function updateExamDetails(exams) {
            let html = '';
            let prevExam = null;

            exams.forEach((exam, index) => {
                // 计算差值
                const scoreDiff = index > 0 ? exam.score - prevExam.score : null;
                const classRankDiff = index > 0 ? prevExam.classRank - exam.classRank : null;
                const gradeRankDiff = index > 0 ? prevExam.gradeRank - exam.gradeRank : null;

                // 格式化差值显示
                const formatDiff = (diff, isScore = false) => {
                    if (diff === null) return '-';

                    if (diff === 0) {
                        return `<span class="change-trend"><i class="fas fa-minus"></i>0</span>`;
                    }

                    if (diff > 0) {
                        // 分数上升或排名上升
                        const symbol = isScore ? '+' : '';
                        return `<span class="change-trend improvement"><i class="fas fa-arrow-up"></i>${symbol}${diff}</span>`;
                    } else {
                        // 分数下降或排名下降
                        return `<span class="change-trend decline"><i class="fas fa-arrow-down"></i>${Math.abs(diff)}</span>`;
                    }
                };

                html += `
                    <tr>
                        <td>${exam.examName}</td>
                        <td>${exam.score}</td>
                        <td>${formatDiff(scoreDiff, true)}</td>
                        <td>${exam.classRank}</td>
                        <td>${formatDiff(classRankDiff)}</td>
                        <td>${exam.gradeRank}</td>
                        <td>${formatDiff(gradeRankDiff)}</td>
                    </tr>
                `;

                // 更新前一次考试数据
                prevExam = exam;
            });

            if (html === '') {
                html = '<tr><td colspan="7">暂无考试数据</td></tr>';
            }

            examDetailsEl.innerHTML = html;
        }

        // 渲染成绩趋势图
        function renderPerformanceChart(exams) {
            // 初始化图表
            const chart = echarts.init(performanceChart);

            // 准备图表数据
            const examNames = exams.map(exam => exam.examName);
            const scores = exams.map(exam => exam.score);
            const classRanks = exams.map(exam => exam.classRank);
            const gradeRanks = exams.map(exam => exam.gradeRank);

            // 计算差值数据
            const scoreDiffs = exams.map((exam, index) =>
                index > 0 ? exam.score - exams[index - 1].score : null
            );

            const classRankDiffs = exams.map((exam, index) =>
                index > 0 ? exams[index - 1].classRank - exam.classRank : null
            );

            const gradeRankDiffs = exams.map((exam, index) =>
                index > 0 ? exams[index - 1].gradeRank - exam.gradeRank : null
            );

            // 图表配置
            const option = {
                tooltip: {
                    trigger: 'axis',
                    formatter: function (params) {
                        const scoreParam = params.find(p => p.seriesName === '成绩');
                        const classParam = params.find(p => p.seriesName === '班级排名');
                        const gradeParam = params.find(p => p.seriesName === '年级排名');

                        let html = `<div style="margin-bottom:5px"><strong>${params[0].axisValue}</strong></div>`;
                        if (scoreParam) {
                            html += `<div>成绩: ${scoreParam.value}分</div>`;
                        }
                        if (classParam) {
                            html += `<div>班级排名: 第${classParam.value}名</div>`;
                        }
                        if (gradeParam) {
                            html += `<div>年级排名: 第${gradeParam.value}名</div>`;
                        }

                        // 添加变化信息
                        const index = params[0].dataIndex;
                        if (index > 0) {
                            html += `<div style="margin-top:5px;border-top:1px dashed #eee;padding-top:5px">`;

                            if (scoreDiffs[index] !== null) {
                                const diff = scoreDiffs[index];
                                const color = diff > 0 ? '#ff4d4f' : '#52c41a';
                                const icon = diff > 0 ? '↑' : '↓';
                                html += `<div>成绩变化: <span style="color:${color}">${icon}${Math.abs(diff)}分</span></div>`;
                            }

                            if (classRankDiffs[index] !== null) {
                                const diff = classRankDiffs[index];
                                const color = diff > 0 ? '#ff4d4f' : '#52c41a';
                                const icon = diff > 0 ? '↑' : '↓';
                                const direction = diff > 0 ? '上升' : '下降';
                                html += `<div>班级排名变化: <span style="color:${color}">${icon}${Math.abs(diff)}名 (${direction})</span></div>`;
                            }

                            html += `</div>`;
                        }

                        return html;
                    }
                },
                legend: {
                    data: ['成绩', '班级排名', '年级排名'],
                    bottom: 10
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '15%',
                    top: '10%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: examNames
                },
                yAxis: [
                    {
                        type: 'value',
                        name: '成绩',
                        min: function (value) {
                            return Math.max(0, Math.floor(value.min - 10));
                        },
                        position: 'left',
                        axisLine: {
                            lineStyle: {
                                color: '#5470c6'
                            }
                        }
                    },
                    {
                        type: 'value',
                        name: '排名',
                        inverse: true,
                        min: 1,
                        position: 'right',
                        axisLine: {
                            lineStyle: {
                                color: '#91cc75'
                            }
                        }
                    }
                ],
                series: [
                    {
                        name: '成绩',
                        type: 'line',
                        smooth: true,
                        data: scores,
                        yAxisIndex: 0,
                        lineStyle: {
                            width: 4
                        },
                        symbolSize: 10,
                        itemStyle: {
                            color: '#5470c6'
                        },
                        markPoint: {
                            data: [
                                { type: 'max', name: '最高分' },
                                { type: 'min', name: '最低分' }
                            ]
                        }
                    },
                    {
                        name: '班级排名',
                        type: 'line',
                        smooth: true,
                        data: classRanks,
                        yAxisIndex: 1,
                        symbolSize: 8,
                        itemStyle: {
                            color: '#91cc75'
                        }
                    },
                    {
                        name: '年级排名',
                        type: 'line',
                        smooth: true,
                        data: gradeRanks,
                        yAxisIndex: 1,
                        symbolSize: 8,
                        itemStyle: {
                            color: '#fac858'
                        }
                    }
                ]
            };

            chart.setOption(option);

            // 响应窗口大小变化
            window.addEventListener('resize', function () {
                chart.resize();
            });
        }

        // 筛选数据
        function filterData() {
            const selectedClass = classSelect.value;
            const searchTerm = searchInput.value.toLowerCase();

            let filteredData = [...currentData];

            if (selectedClass !== 'all') {
                filteredData = filteredData.filter(student =>
                    student.class && student.class.toString() === selectedClass.toString()
                );
            }

            if (searchTerm) {
                filteredData = filteredData.filter(student => {
                    const name = student.name ? student.name.toString().toLowerCase() : '';
                    const id = student.id ? student.id.toString().toLowerCase() : '';
                    const seat = student.seat ? student.seat.toString().toLowerCase() : '';
                    return name.includes(searchTerm) || id.includes(searchTerm) || seat.includes(searchTerm);
                });
            }

            updateStats(filteredData);
            renderTable(filteredData);
        }

        // 文件上传处理
        fileInput.addEventListener('change', function (e) {
            const file = e.target.files[0];
            if (!file) return;

            showInitialEmptyState('正在处理文件...');

            const reader = new FileReader();
            reader.onload = function (e) {
                try {
                    const data = new Uint8Array(e.target.result);
                    const workbook = XLSX.read(data, { type: 'array' });

                    if (workbook.SheetNames.length === 0) {
                        throw new Error('Excel文件不包含有效工作表');
                    }

                    const worksheet = workbook.Sheets[workbook.SheetNames[0]];
                    const jsonData = XLSX.utils.sheet_to_json(worksheet);

                    if (jsonData.length === 0) {
                        throw new Error('Excel文件不包含有效数据');
                    }

                    const processedData = processExcelData(jsonData);
                    processData(processedData);
                } catch (error) {
                    console.error('文件处理错误:', error);
                    alert(`文件处理失败: ${error.message}\n请确保文件格式正确`);
                    showInitialEmptyState();
                }
            };
            reader.onerror = function (e) {
                console.error('文件读取错误:', e);
                alert('文件读取失败，请重试');
                showInitialEmptyState();
            };
            reader.readAsArrayBuffer(file);
        });

        // 模拟文件上传功能
        document.querySelector('.file-upload-btn').addEventListener('click', function () {
            if (!fileInput.files.length) {
                fileInput.click();
            }
        });

        // 新增功能：更新数据
        updateBtn.addEventListener('click', function () {
            showInitialEmptyState('正在更新数据...');
            fetchExcelData().then(networkData => {
                if (networkData) {
                    const processedData = processExcelData(networkData);
                    processData(processedData);
                } else {
                    showInitialEmptyState('网络请求失败，请手动上传文件');
                }
            });
        });

        // 新增功能：重置数据
        resetBtn.addEventListener('click', function () {
            if (confirm('确定要重置所有数据吗？')) {
                currentData = [];
                localStorage.removeItem(STORAGE_KEY);
                updateStats([]);
                updateClassSelect([]);
                renderTable([]);
                showInitialEmptyState('数据已重置');
            }
        });

        // 新增功能：导出数据
        exportBtn.addEventListener('click', function () {
            if (currentData.length === 0) {
                alert('没有可导出的数据');
                return;
            }

            const workbook = XLSX.utils.book_new();
            // 直接使用中文表头对应的字段生成数据，不再额外添加英文表头行
            const exportData = currentData.map(student => ({
                班级: student.class,
                姓名: student.name,
                考号: student.id,
                座号: student.seat
            }));
            const worksheet = XLSX.utils.json_to_sheet(exportData);
            XLSX.utils.book_append_sheet(workbook, worksheet, '学生数据');

            const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
            const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = '学生数据.xlsx';
            a.click();
            window.URL.revokeObjectURL(url);
        });

        // 关闭模态框
        closeModalBtn.addEventListener('click', function () {
            studentModal.classList.remove('active');
        });

        // 点击模态框外部关闭
        studentModal.addEventListener('click', function (e) {
            if (e.target === studentModal) {
                studentModal.classList.remove('active');
            }
        });

        // 初始化页面
        document.addEventListener('DOMContentLoaded', function () {
            const localData = loadLocalData();
            if (localData) {
                processData(localData);
            } else {
                fetchExcelData().then(networkData => {
                    if (networkData) {
                        const processedData = processExcelData(networkData);
                        processData(processedData);
                    } else {
                        showInitialEmptyState('网络请求失败，请手动上传文件');
                    }
                });
            }

            // 初始化模态框状态
            studentModal.classList.remove('active');
        });
    </script>
</body>

</html>